#pragma once

#include <iostream>

#include "CommonParent.h"
#include "Utilities.h"

CommonParent::CommonParent(void){
	commonWhile = Type::Map::ParentMatrix();
	commonIf = Type::Map::ParentMatrix();
}
CommonParent::~CommonParent(void){
	clear();
}

void CommonParent::clear(){
	commonWhile.clear();
	commonIf.clear();
}

// set the bitmap (square matrix) for parent-parent of common parent between 2 lines
bool CommonParent::setCommon(Type::Entity::Line entity, Type::Map::ParentMatrix& parentMatrix){
	if(!Utilities::isvalidParentMatrix(parentMatrix)){
		return false;
	}

	if(entity == Type::Entity::WHILE_LINE_ENTITY){
		commonWhile = parentMatrix;
	}else if(entity == Type::Entity::IF_LINE_ENTITY){
		commonIf = parentMatrix;
	}else{
		return false;
	}

	return true;
}


// get the common parent of parent 1 and 2,
Type::Index::Line CommonParent::getCommon(Type::Entity::Line entity, 
	Type::Index::Line parentOne, Type::Index::Line parentTwo){
		
		// when parent 1 or 2 are invalid
		if(!Utilities::isValidLineIndex(parentOne) || !Utilities::isValidLineIndex(parentTwo)){
			return -1;
		}
			
		if(entity==Type::Entity::WHILE_LINE_ENTITY && !commonWhile.empty()){
			// if parent 1 exists in indices of the first column
			if(commonWhile.find(parentOne) != commonWhile.end()){
				Type::Map::ParentMap row = commonWhile.at(parentOne);

				// if parent 2 exists in the row of parent 1
				if(row.find(parentTwo) != row.end()){
					return row.at(parentTwo);
				}
			}
		}else if(entity==Type::Entity::IF_LINE_ENTITY && !commonIf.empty()){
			// if parent 1 exists in indices of the first column
			if(commonIf.find(parentOne) != commonIf.end()){
				Type::Map::ParentMap row = commonIf.at(parentOne);

				// if line 2 exists in the row of parent 1
				if(row.find(parentTwo) != row.end()){
					return row.at(parentTwo);
				}
			}
		}
		return -1;
}

// check if the common parent of parent 1 and 2 matches the given parent
bool CommonParent::isCommon(Type::Entity::Line entity, Type::Index::Line parentOne, 
	Type::Index::Line parentTwo, Type::Index::Line parent){
		// when parent 1 or 2 are invalid
		if(!Utilities::isValidLineIndex(parentOne) || !Utilities::isValidLineIndex(parentTwo)){
			return false;
		}

		// check if the given parent matches the stored parent
		Type::Index::Line commonParent = getCommon(entity, parentOne, parentTwo);
		return commonParent != -1 && commonParent == parent;
}